package com.xian.im.modules.sensitive.handler;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.hash.Funnel;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.modules.sensitive.load.SensitiveLoad;
import com.xian.im.modules.sensitive.service.RedisService;
import com.xian.im.modules.sensitive.suporrt.RedisBloomFilterHelper;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-02-23 09:29
 **/
public class RedisBloomHandler implements SensitiveBloom {
    private static RedisBloomFilterHelper<String> myBloomFilterHelper = new RedisBloomFilterHelper<>((Funnel<String>) (from, into) -> into.putString(from, Charsets.UTF_8).putString(from, Charsets.UTF_8), 150000, 0.0001);

    Executor executor = Executors.newSingleThreadExecutor();
    /**
     * 初始化敏感词库
     *
     * @param \
     * @return
     */
    @Override
    public boolean loadSensitive() {
        RedisService redisService = SpringContextHolder.getBean(RedisService.class);
        Boolean o = redisService.exist(getType());
        if(!o){
            List<String> list = new ArrayList<>(SensitiveLoad.getInstance().container());
            List<List<String>> parts = Lists.partition(list, 50);
            parts.stream().forEach(l -> {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        redisService.addByBloomFilter(myBloomFilterHelper,getType(),l);
                    }
                });
            });
        }
        return Boolean.TRUE;
    }

    /**
     * 布隆类型
     */
    @Override
    public String getType() {
        return REDIS_TYPE;
    }

    /**
     * 添加敏感词
     *
     * @param word
     * @return
     */
    @Override
    public Boolean add(String word) {
        RedisService redisService = SpringContextHolder.getBean(RedisService.class);
        redisService.addByBloomFilter(myBloomFilterHelper,getType(),word);
        return Boolean.TRUE;
    }

    /**
     * 添加敏感词
     *
     * @param words
     * @return
     */
    @Override
    public Boolean addAll(Collection<String> words) {
        RedisService redisService = SpringContextHolder.getBean(RedisService.class);
        redisService.addByBloomFilter(myBloomFilterHelper,getType(),words);
        return Boolean.TRUE;
    }

    /**
     * 判断是否是敏感词
     *
     * @param word
     * @return
     */
    @Override
    public Boolean includeByBloomFilter(String word) {
        RedisService redisService = SpringContextHolder.getBean(RedisService.class);
        return redisService.includeByBloomFilter(myBloomFilterHelper,getType(),word);
    }

    /**
     * @return
     */
    @Override
    public Boolean reset() {
        return null;
    }
}
